import { createRouter, createWebHashHistory } from 'vue-router'
import { CONFIG } from '../config/index.js'
import userRoutes from './user.js'
import clusterRoutes from './cluster.js'
import nodeRoutes from './node.js'
import namespaceRoutes from './namespace.js'
import { podRoutes,deploymentRoutes,statefulsetRoutes,cronjobRoutes,daemonsetRoutes } from './scheduling.js'
import { serviceRoutes, ingressRoutes, endpointRoutes } from './pubilishing.js'
import { configmapRoutes, secretRoutes } from './configuration.js'
import { pvRoutes, pvcRoutes } from './storage.js'
import toolsRoutes from './tools.js'
const Login = () => import('../views/Login.vue')
const Layout = () => import('../views/layout/Layout.vue')


// 定义路由映射
const routes = [
    userRoutes,
    clusterRoutes,
    nodeRoutes,
    namespaceRoutes,
    podRoutes,
    deploymentRoutes,
    statefulsetRoutes, cronjobRoutes, daemonsetRoutes,
    serviceRoutes, ingressRoutes, endpointRoutes,
    configmapRoutes, secretRoutes,
    pvRoutes, pvcRoutes, toolsRoutes,
    {
        path: "/login",
        component: Login
    },
    {
        path: "/",
        component: Layout,
        children: [
            {
                path: "/",
                component: () => import('../views/Home.vue')
            }
        ]
    },
]

//创建路由实例
const router = createRouter({
    history: createWebHashHistory(),
    routes,
})

// 定义一个全局守卫，用于判断请求链接是否携带token字段
router.beforeEach(
    (to, from, next) => {
        // 1.访问的是login，没有token ==> next()
        // 2.访问的是login，已有token ==> next('/')
        // 3.访问非login页面，已有token ==> next()
        // 4.访问的非login页面，没有token ==> next('/login')
        const toPath = to.path //拿到访问路径
        const toLogin = toPath.indexOf("/login") // 找到0 没有找到 -1
        const tokenStatus = window.localStorage.getItem(CONFIG.TOKEN_NAME) // 判断本地是否有token
        if (toLogin == 0 && tokenStatus) {
            next("/")
        }else if (toLogin == 0 && !tokenStatus) {
            next()
        }else if (tokenStatus) {
            next()
        }else {
            next('/login')
        }
    }
)
export default router